<template>
  <div class="search">
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search
        v-model="userKey"
        placeholder="请输入搜索关键词"
        shape="round"
      >
      </van-search>
      <div @click="search">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <p v-for="item in historyList" 
      :key="item"
      @click="searchById(item)">{{item}}</p>
    </div>
    <div class="historyList">
      <h2>搜索结果</h2>
      <router-link :to="{path: `/postDetail/${item.id}`}" 
      v-for="item in searchList" 
      :key="item.id" 
      class="searchResult">{{item.title}}</router-link>
    </div>
  </div>
</template>

<script>
import {searchPost} from '@/apis/post.js'
export default {
    data () {
        return {
            userKey:'',
            searchList:[],
            historyList:[]
        }
    },
    mounted(){
        this.historyList = JSON.parse(localStorage.getItem('searchHistoty')) || []
        console.log(this.historyList);
    },
    methods:{
        searchById(item){
            this.userKey = item
            this.search()
        },
        async search(){
        //    let res = await searchPost({keyword:this.userKey});
        //    console.log(res);
        this.searchList = (await searchPost({keyword:this.userKey})).data.data 
        
         // 如果关键字重复，则先删除，再插入到最前面
         let index = this.historyList.indexOf(this.userKey)
         if(index !== -1){
             this.historyList.splice(index,1)
         }
         // 设置最多的数量 4
         if(this.historyList.length == 5){
         // pop:删除数组中的最后一个元素
             this.historyList.pop()
         }
         this.historyList.unshift(this.userKey)

        // 存储关键字
        localStorage.setItem('searchHistoty',JSON.stringify(this.historyList))
        }
    }
}
</script>

<style lang="less" scoped>
.header{
    display: flex;
    height: 50px;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    border-bottom: 1px solid #ccc;
    .van-search{
      flex: 1;
      padding: 5px 12px;
    }
  }
  .historyList{
    padding:10px;
    border-bottom: 1px solid #ccc;
    overflow: hidden;
    h2{
      line-height: 40px;
      font-weight: bold;
    }
    > a {
      display: block;
      text-decoration: underline;
      line-height: 30px;
      color:#666;
    }
    p {
    width: 20%;
    margin-right: 10px;
    border: dashed #ddd 1px;
    text-align: center;
    float: left;
    line-height: 30px;
  }
  }
  .searchResult {
  padding-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>